package com.yunxi.service.dubboService.impl.sat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yunxi.baseDataToHub.pojo.urm.DeliveryVehicleVO;
import com.yunxi.baseDataToHub.pojo.urm.UrmHandleVehicleVO;
import com.yunxi.baseDataToHub.service.urm.UrmDubboService;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sat.*;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.order.service.OrderActualSalesDubboService;
import com.yunxi.sat.pojo.*;
import com.yunxi.sat.service.HandleVehicleDubboService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.sat.*;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.sto.service.VehiclePdiBillDubboService;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.service.StaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 交车信息 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-07-15
 */
public class HandleVehicleDubboServiceImpl implements HandleVehicleDubboService {
    private static final Logger logger = LoggerFactory.getLogger(HandleVehicleDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "handleVehicleServiceImpl")
    HandleVehicleService handleVehicleService;

    @Autowired
    @Qualifier(value = "satCustomerFollowServiceImpl")
    SatCustomerFollowService satCustomerFollowService;

    @Autowired
    @Qualifier(value = "satCustomerClueServiceImpl")
    SatCustomerClueService satCustomerClueService;

    @Autowired
    @Qualifier(value = "orderActualSalesDubboServiceImpl")
    OrderActualSalesDubboService orderActualSalesDubboService;

    @Autowired
    UrmDubboService urmDubboServiceImplBiz;

    @Autowired
    @Qualifier(value = "msgTemplateServiceImpl")
    MsgTemplateService msgTemplateService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "staffDubboServiceBiz")
    StaffDubboService staffDubboService;

    @Autowired
    @Qualifier(value = "orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    VehiclePdiBillDubboService vehiclePdiBillDubboService;

    @Override
    public HandleVehicleVO getById(String id) throws Exception {
        HandleVehicle handleVehicle = handleVehicleService.getById(id);
        if(handleVehicle != null){
            HandleVehicleVO handleVehicleVO = new HandleVehicleVO();
            BeanUtils.copyProperties(handleVehicle, handleVehicleVO);
            return handleVehicleVO;
        }
        else{
            throw new Exception("操作失败,无法根据id:找到对应交车记录!");
        }
    }

    @Override
    public void saveOrUpdate(HandleVehicleVO handleVehicleVO,LoginInfo loginInfo) throws Exception {
        handleVehicleVO.setPartnerCode(loginInfo.getPartnerCode());
        handleVehicleVO.setCreateBy(loginInfo.getUserCode());
        handleVehicleVO.setUpdateBy(loginInfo.getUserCode());
        handleVehicleVO.setSalesConsultantNo(loginInfo.getUserCode());
        HandleVehicle handleVehicle = new HandleVehicle();
        BeanUtils.copyProperties(handleVehicleVO, handleVehicle);
        handleVehicleService.saveOrUpdate(handleVehicle);

        //设置URM交车信息字段
        DeliveryVehicleVO deliveryVehicleVO = setHandleVehicleInfoURM(handleVehicleVO);
        //发送交车信息到URM
        sendHandleVehicleInfo2URM(deliveryVehicleVO);

        //生成消息给交车专员
        msgPush(handleVehicleVO, loginInfo);
    }

    /**
     * 生成消息
     * @param handleVehicleVO
     * @param loginInfo
     */
    private void msgPush(HandleVehicleVO handleVehicleVO, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {
        ApiResult rolePartnerHandleVehicle = staffDubboService.listStaffByRoleCode("rolePartnerHandleVehicle", loginInfo);
        List<StaffVO> list = (List<StaffVO>)rolePartnerHandleVehicle.getData();
        SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
        satCustomerClueVO.setCustomerNo(handleVehicleVO.getCustomerNo());
        satCustomerClueVO.setPartnerCode(loginInfo.getPartnerCode());
        String customerName = satCustomerClueService.getCustomerNameByNo(satCustomerClueVO);
        if(list != null && list.size() > 0){
            for(StaffVO vo : list){
                SatMessAddVO satMessAddVO = new SatMessAddVO();
                satMessAddVO.setType("5");
                satMessAddVO.setTemplateType(21);
                satMessAddVO.setCustomerName(customerName);
                satMessAddVO.setCustomerNo(handleVehicleVO.getCustomerNo());
                satMessAddVO.setSalesConsultantNo(vo.getAccountNo());
                satMessAddVO.setReceiveRoleCode("rolePartnerHandleVehicle");
                satMessAddVO.setOperaRoleCode(loginInfo.getRoleCode());
                satMessService.newMess(satMessAddVO);
            }
        }
    }

    private void sendHandleVehicleInfo2URM(DeliveryVehicleVO deliveryVehicleVO) throws Exception {
        ApiResult apiResult = null;
        try {
            apiResult = urmDubboServiceImplBiz.sendDeliveryVehiclePMS2Urm(deliveryVehicleVO);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        if (200 != apiResult.getCode()) {
            logger.error("URM接口执行，同步试乘试驾信息失败，事务回滚!");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception( "URM接口执行，同步试乘试驾信息失败");
        }
        if (apiResult.getData()!=null ){
            JSON.parseObject((String) apiResult.getData());
        }
    }

    private DeliveryVehicleVO setHandleVehicleInfoURM(HandleVehicleVO handleVehicleVO) {
        DeliveryVehicleVO deliveryVehicleVO = new DeliveryVehicleVO();
        deliveryVehicleVO.setPartnerCode(handleVehicleVO.getPartnerCode());//渠道商代码
        deliveryVehicleVO.setHandleStatus(handleVehicleVO.getHandleStatus());//交车状态
        deliveryVehicleVO.setOrderCustomerNo(handleVehicleVO.getOrderCustomerNo());//零售订单号
        deliveryVehicleVO.setCustomerNo(handleVehicleVO.getCustomerNo());//客户编号
        Date handleTime = handleVehicleVO.getHandleTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(handleTime != null){
            String format = simpleDateFormat.format(handleTime);
            deliveryVehicleVO.setHandleTime(format);//预计交车时间
        }
        deliveryVehicleVO.setHandleUser(handleVehicleVO.getHandleUser());//交车人
        Date beginHandleTime = handleVehicleVO.getBeginHandleTime();
        if(beginHandleTime != null){
            String format2 = simpleDateFormat.format(beginHandleTime);
            deliveryVehicleVO.setBeginHandleTime(format2);//开始交车时间
        }
        Date finishDate = handleVehicleVO.getFinishDate();
        if(finishDate != null ){
            String format3 = simpleDateFormat.format(finishDate);
            deliveryVehicleVO.setFinishDate(format3);//交车完成时间
        }
        deliveryVehicleVO.setHandleStyle(handleVehicleVO.getHandleStyle());//交车方式
        deliveryVehicleVO.setHandlePic1(handleVehicleVO.getHandlePic1());//交车拍照
        deliveryVehicleVO.setHandlePic2(handleVehicleVO.getHandlePic2());//交车确认单
        deliveryVehicleVO.setHandlePic3(handleVehicleVO.getHandlePic3());//材料交接单
        deliveryVehicleVO.setSalesConsultantNo(handleVehicleVO.getSalesConsultantNo());//销售顾问编号
        return deliveryVehicleVO;
    }

    @Override
    public void removeById(String id) {
        handleVehicleService.removeById(id);
    }

    @Override
    public PageInfo<HandleVehicleVO> findPageByVO(HandleVehicleVO handleVehicleVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) throws Exception {
        String roleCode = loginInfo.getRoleCode();
        if(StringUtils.isNotEmpty(roleCode) && roleCode.equals(DictConstant.USER_ROLE_HANDLE_VEHICLE)){
            handleVehicleVO.setHandleUser(loginInfo.getUserCode());
        }
        else{
            handleVehicleVO.setPartnerCode(loginInfo.getPartnerCode());
        }
        PageInfo<HandleVehicleVO> pageInfo = handleVehicleService.pageByVo(handleVehicleVO, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public void removeByListVo(List<HandleVehicleVO> handleVehicleVOList) throws Exception {
        handleVehicleService.removeByListVo(handleVehicleVOList);
    }

    @Override
    public List listByVo(HandleVehicleVO handleVehicleVO) {
        return handleVehicleService.listByVo(handleVehicleVO);
    }

    @Override
    public void del(List<String> list, String updateBy) throws Exception {
        if(list != null && list.size() > 0){
            for (String id : list){
                HandleVehicle byId = handleVehicleService.getById(id);
                if(byId != null){
                    byId.setIsDel(1);
                    byId.setUpdateBy(updateBy);
                    handleVehicleService.saveOrUpdate(byId);
                }
                else{
                    throw new Exception("操作失败,无法根据id:"+id+"找到对应交车记录!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
    }

    /**
     * 交车完成
     * @param handleVehicleVO
     * @param handleUser
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void complete(HandleVehicleVO handleVehicleVO, String handleUser,LoginInfo loginInfo) throws Exception {
        String customerNo = handleVehicleVO.getCustomerNo();
        handleVehicleVO.setPartnerCode(loginInfo.getPartnerCode());
        if(StringUtil.isNotEmpty(handleVehicleVO.getHandleId())&&StringUtil.isNotEmpty(customerNo)){
            HandleVehicle handleVehicle = handleVehicleService.getById(handleVehicleVO.getHandleId());
            if(handleVehicle != null ){
                handleVehicle.setHandleTime(handleVehicleVO.getHandleTime());
                handleVehicle.setHandleUser(handleVehicleVO.getHandleUser());
                handleVehicle.setHandleStyle(handleVehicleVO.getHandleStyle());
                handleVehicle.setHandlePic1(handleVehicleVO.getHandlePic1());
                handleVehicle.setHandlePic2(handleVehicleVO.getHandlePic2());
                handleVehicle.setHandlePic3(handleVehicleVO.getHandlePic3());
                handleVehicle.setHandleUser(handleUser);
                handleVehicle.setFinishDate(new Date());
                handleVehicle.setHandleStatus(2);//交车完成
                //1.更新交车单状态完成
                handleVehicleService.saveOrUpdate(handleVehicle);
                //4.新增实销数据
                try {
                    orderActualSalesDubboService.saveOrderActualSales(handleVehicle.getOrderCustomerNo(),loginInfo);
                }
                catch (Exception e){
                    throw new Exception(e);
                }

                //2.生成消息给销售顾问
                msgPushToS(loginInfo, handleVehicle);
                //3.变更客户状态为基盘客户
                SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
                satCustomerFollowVO.setCustomerNo(customerNo);
                satCustomerFollowVO.setCustStatus(3);
                satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
                satCustomerFollowService.updateCustomerLevel(satCustomerFollowVO);

                //获取订单里的VIN,更新车辆库存状态
                updateStockStatus(handleVehicle);
            }



            //2.根据客户编号查询是否有待跟进记录,有则更新为老客户跟进
            //没有则新增一条老客户跟进
            QueryWrapper<SatCustomerFollow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CUSTOMER_NO",handleVehicleVO.getCustomerNo());
            queryWrapper.eq("FOLLOW_STATUS",0);//待跟进
            List<SatCustomerFollow> list = satCustomerFollowService.list(queryWrapper);
            if(list != null){
                for (SatCustomerFollow satCustomerFollow : list){
                    satCustomerFollow.setIsOldCustomerFollow(1);
                    satCustomerFollowService.updateById(satCustomerFollow);
                }
            }
            else{
                //新增老客户跟进
                newCustomerFollow(handleVehicleVO);
            }

            //设置URM交车信息字段
            UrmHandleVehicleVO urmHandleVehicleVO = setHandleVehicleURM(handleVehicle);
            //发送交车信息到URM
            sendHandleVehicle2URM(urmHandleVehicleVO);
        }
        else{
            throw new Exception("操作失败,参数主键handleId或客户编号custoemrNo为空!");
        }
    }

    /**
     * 更新车辆库存状态
     * @param handleVehicle
     */
    private void updateStockStatus(HandleVehicle handleVehicle) throws Exception{
        String orderCustomerNo = handleVehicle.getOrderCustomerNo();
        QueryWrapper<OrderCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_CUSTOMER_NO",orderCustomerNo);
        OrderCustomer orderCustomer = orderCustomerService.getOne(queryWrapper);
        if(orderCustomer != null){
            String vin = orderCustomer.getVin();
            //更新车辆库存
            QueryWrapper<PmsVehicleStock> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("VIN",vin);
            PmsVehicleStock vehicleStock = vehicleStockMService.getOne(queryWrapper1);
            if(vehicleStock != null){
                vehicleStock.setStorageCode(null);//清空仓库
                vehicleStock.setStorageStatus(2);//出库
                vehicleStock.setOutStockDate(new Date());//出库日期
                vehicleStockMService.saveOrUpdate(vehicleStock);
            }
            //更新车辆下线记录
            QueryWrapper<VehicleOffline> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("VIN",vin);
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper2);
            if(vehicleOffline != null){
                vehicleOffline.setStorageStatus(2);//出库
                vehicleOffline.setCarState(DictConstant.VEHICLE_TURN_STATE_15LSCK);
                vehicleOfflineService.saveOrUpdate(vehicleOffline);
            }
            //推送零售出库到APP
            vehiclePdiBillDubboService.sentMsgToApp(vin,DictConstant.APP_RPNAME_VDC_SOUT,DictConstant.APP_CODE_07);
        }
    }

    private UrmHandleVehicleVO setHandleVehicleURM(HandleVehicle handleVehicle) throws InvocationTargetException, IllegalAccessException {
        UrmHandleVehicleVO urmHandleVehicleVO = new UrmHandleVehicleVO();
        if(handleVehicle != null){
            org.apache.commons.beanutils.BeanUtils.copyProperties(urmHandleVehicleVO,handleVehicle);
            Date handleTime = handleVehicle.getHandleTime();
            Date beginHandleTime = handleVehicle.getBeginHandleTime();
            Date finishDate = handleVehicle.getFinishDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(handleTime != null){
                String handleTimeStr = simpleDateFormat.format(handleTime);
                urmHandleVehicleVO.setHandleTime(handleTimeStr);
            }
            if(beginHandleTime != null){
                String beginHandleTimeStr = simpleDateFormat.format(beginHandleTime);
                urmHandleVehicleVO.setBeginHandleTime(beginHandleTimeStr);
            }
            if(finishDate != null){
                String finishDateStr = simpleDateFormat.format(finishDate);
                urmHandleVehicleVO.setFinishDate(finishDateStr);
            }
        }
        return urmHandleVehicleVO;
    }

    private void sendHandleVehicle2URM(UrmHandleVehicleVO urmHandleVehicleVO) throws Exception {
        ApiResult apiResult = null;
        try {
            apiResult = urmDubboServiceImplBiz.sendHandleVehiclePMS2Urm(urmHandleVehicleVO);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        if (200 != apiResult.getCode()) {
            logger.error("URM接口执行，同步交车信息失败，事务回滚!");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception( "URM接口执行，同步交车信息失败");
        }
        if (apiResult.getData()!=null ){
            JSON.parseObject((String) apiResult.getData());
        }
    }


    /**
     * 开始交车
     * @param handleVehicleVO
     * @throws Exception
     */
    @Override
    public void begin(HandleVehicleVO handleVehicleVO) throws Exception {
        String handleId = handleVehicleVO.getHandleId();
        HandleVehicle handleVehicle = handleVehicleService.getById(handleId);
        if(handleVehicle == null)throw new Exception("操作失败,无法根据主键:"+handleId+"找到对应交车记录!");
        handleVehicle.setHandleTime(handleVehicleVO.getHandleTime());
        handleVehicle.setBeginHandleTime(new Date());
        //校验相同交车专员,交车时间是否重复(两小时一个交车)
        Integer handleCount = handleVehicleService.queryRepeatHandle(handleVehicleVO);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
        String handleTimeStr = simpleDateFormat.format(handleVehicleVO.getHandleTime());
        if(handleCount > 0)throw new Exception("操作失败,"+handleTimeStr+"已存在交车任务");
        handleVehicleService.saveOrUpdate(handleVehicle);
    }


    /**
     * 销售顾问月目标
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public TaskTargetVO taskTarget(String queryDate,LoginInfo loginInfo) throws Exception {
        Object staff = loginInfo.getStaff();
        String positionCode = null;
        if(staff != null){
            StaffVO staffVO = JSONObject.parseObject(JSONObject.toJSONString(staff), StaffVO.class);
            positionCode = staffVO.getPositionCode();
        }
        TaskTargetVO taskTargetVO = new TaskTargetVO();
        Object partner = loginInfo.getPartner();
        if(partner != null){
            PartnerVO partnerVO = new PartnerVO();
            org.apache.commons.beanutils.BeanUtils.copyProperties(partnerVO,partner);
            taskTargetVO.setPartnerCode(partnerVO.getPartnerCode());
        }
        taskTargetVO.setSalesConsultantNo(loginInfo.getUserCode());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(queryDate);
        taskTargetVO.setQueryDate(parse);

        // 总经理、销售经理、管理员 查看全店；否则按登录账号查询
        if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && (
            DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode()) || DictConstant.USER_ROLE_PARTNER_MANAGER
                .equals(loginInfo.getRoleCode()) || DictConstant.USER_ROLE_PARTNER_ADMIN
                .equals(loginInfo.getRoleCode()))) {
            return handleVehicleService.managerTaskTarget(taskTargetVO);
        }
        return handleVehicleService.taskTarget(taskTargetVO);

//        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
//            return handleVehicleService.taskTarget(taskTargetVO);
//        }
//        else if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode())){
//            return handleVehicleService.managerTaskTarget(taskTargetVO);
//        }
//        return handleVehicleService.managerTaskTarget(taskTargetVO);
    }

    @Override
    public List<HandleVehicleVO> allList(HandleVehicleVO handleVehicleVO, LoginInfo loginInfo) throws Exception {
        Object staff = loginInfo.getStaff();
        String positionCode = null;
        if(staff != null){
            StaffVO staffVO = JSONObject.parseObject(JSONObject.toJSONString(staff), StaffVO.class);
            positionCode = staffVO.getPositionCode();
        }
        handleVehicleVO.setPartnerCode(loginInfo.getPartnerCode());
        // 非总经理、非销售经理则按登录账号查询
        if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && !DictConstant.USER_ROLE_MANAGER
            .equals(loginInfo.getRoleCode()) && !DictConstant.USER_ROLE_PARTNER_MANAGER
            .equals(loginInfo.getRoleCode())) {
            handleVehicleVO.setSalesConsultantNo(loginInfo.getUserCode());
        }
        handleVehicleVO.setActualHandleTime(new Date());
        return handleVehicleService.allList(handleVehicleVO);
    }

    @Override
    public HandleVehicleVO getInfoById(String handleId) throws Exception {
        HandleVehicleVO vo = handleVehicleService.getInfoById(handleId);
        if(vo != null && StringUtils.isNotEmpty(vo.getOrderPicPath())){
            String[] split = vo.getOrderPicPath().split(",");
            List<String> list = Arrays.asList(split);
            vo.setOrderPicPathList(list);
        }
        return vo;
    }

    @Override
    public HandleVehicleVO handleInfo(String customerNo) throws Exception {
        HandleVehicleVO handleVehicleVO = handleVehicleService.handleInfo(customerNo);
        if(handleVehicleVO != null && StringUtils.isNotEmpty(handleVehicleVO.getOrderPicPath())){
            String[] split = handleVehicleVO.getOrderPicPath().split(",");
            List<String> list = Arrays.asList(split);
            handleVehicleVO.setOrderPicPathList(list);
        }
        return handleVehicleVO;
    }

    /**
     * 待交车时间列表
     * @param userCode
     * @param partnerCode
     * @return
     * @throws Exception
     */
    @Override
    public List<Date> handleDateList(String userCode, String partnerCode) throws Exception {
        QueryWrapper<HandleVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("HANDLE_USER",userCode);
        queryWrapper.eq("PARTNER_CODE",partnerCode);
        queryWrapper.eq("HANDLE_STATUS",1);
        List<HandleVehicle> list = handleVehicleService.list(queryWrapper);
        List<Date> list1 = new ArrayList<>();
        if(list != null && list.size() > 0){
            for (HandleVehicle handleVehicle : list){
                list1.add(handleVehicle.getHandleTime());
            }
        }
        return list1;
    }


    /**
     * 设置渠道商代码
     * @param handleVehicleVO
     * @param loginInfo
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
//    private void setPartnerCode(HandleVehicleVO handleVehicleVO, LoginInfo loginInfo) throws IllegalAccessException, InvocationTargetException {
//        handleVehicleVO.setPartnerCode(loginInfo.getPartnerCode());
//    }

    /**
     * 新增老客户跟进
     * @param handleVehicleVO
     * @throws Exception
     */
    private void newCustomerFollow(HandleVehicleVO handleVehicleVO) throws Exception {
        String customerLevel = handleVehicleService.getCustomerLevel(handleVehicleVO);
        SatCustomerFollow satCustomerFollow = new SatCustomerFollow();
        satCustomerFollow.setFollowStatus(0);//待跟进
        satCustomerFollow.setCustomerNo(handleVehicleVO.getCustomerNo());
        satCustomerFollow.setPartnerCode(handleVehicleVO.getPartnerCode());
        satCustomerFollow.setLevel(customerLevel);//跟进前客户级别
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,30);// TODO 厂端定义老客户跟进天数
        date = calendar.getTime();
        satCustomerFollow.setPlanFollowTime(date);//计划跟进时间
        satCustomerFollow.setIsOldCustomerFollow(1);
        satCustomerFollowService.saveOrUpdate(satCustomerFollow);
    }


    /**
     * 生成消息给销售顾问
     * @param loginInfo
     * @param handleVehicle
     */
    private void msgPushToS(LoginInfo loginInfo, HandleVehicle handleVehicle) throws InvocationTargetException, IllegalAccessException {
        SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
        satCustomerClueVO.setCustomerNo(handleVehicle.getCustomerNo());
        satCustomerClueVO.setPartnerCode(loginInfo.getPartnerCode());
        String customerName = satCustomerClueService.getCustomerNameByNo(satCustomerClueVO);
        SatMessAddVO satMessAddVO = new SatMessAddVO();
        satMessAddVO.setType("51");
        satMessAddVO.setTemplateType(22);
        satMessAddVO.setCustomerName(customerName);
        satMessAddVO.setCustomerNo(handleVehicle.getCustomerNo());
        satMessAddVO.setSalesConsultantNo(handleVehicle.getSalesConsultantNo());
        satMessAddVO.setReceiveRoleCode("rolePartnerSale");
        satMessAddVO.setOperaRoleCode(loginInfo.getRoleCode());
        satMessService.newMess(satMessAddVO);
    }

    /**
     * 通过零售订单号生成待交车
     * @param orderCustomerNo
     * @throws Exception
     */
    @Override
    public void newHandleVehicle(String orderCustomerNo) throws Exception {
        if(StringUtils.isEmpty(orderCustomerNo))throw new Exception("操作失败.零售订单号为空!");
        //查询订单
        QueryWrapper<OrderCustomer> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ORDER_CUSTOMER_NO",orderCustomerNo);
        OrderCustomer orderCustomer = orderCustomerService.getOne(queryWrapper1);
        if(orderCustomer == null)throw new Exception("操作失败,无法根据订单号:"+orderCustomerNo+"找到对应零售订单!");
        QueryWrapper<HandleVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_CUSTOMER_NO",orderCustomerNo);
        queryWrapper.eq("HANDLE_STATUS",1);//待交车
        List<HandleVehicle> list = handleVehicleService.list(queryWrapper);
        if(list == null || list.size() <= 0){
            HandleVehicle handleVehicle = new HandleVehicle();
            handleVehicle.setPartnerCode(orderCustomer.getPartnerCode());
            handleVehicle.setOrderCustomerNo(orderCustomerNo);
            handleVehicle.setCustomerNo(orderCustomer.getCustomerNo());
            handleVehicle.setSalesConsultantNo(orderCustomer.getSalesConsultantNo());
            handleVehicleService.saveOrUpdate(handleVehicle);
        }
    }

    @Override
    public HandleVehicleVO getByOrderCustomerNo(String orderCustomerNo) {
        HandleVehicleVO vo = handleVehicleService.getByOrderCustomerNo(orderCustomerNo);

        if(vo != null && StringUtils.isNotEmpty(vo.getOrderPicPath())){
            String[] split = vo.getOrderPicPath().split(",");
            List<String> list = Arrays.asList(split);
            vo.setOrderPicPathList(list);
        }
        return vo;
    }

    @Override
    public HandleVehicleVO getInfoByOrderCustomerNo(String orderCustomerNo) {
        HandleVehicleVO vo = handleVehicleService.getInfoByOrderCustomerNo(orderCustomerNo);

        if(vo != null && StringUtils.isNotEmpty(vo.getOrderPicPath())){
            String[] split = vo.getOrderPicPath().split(",");
            List<String> list = Arrays.asList(split);
            vo.setOrderPicPathList(list);
        }

        return vo;
    }

}
